package com.gorkr.dfs;

import org.junit.jupiter.api.Test;

/**
 * dfs？
 *
 * @author gorkr
 * @date 2022/09/12 20:15
 **/
public class M200NumberOfIslands {


    public int numIslands(char[][] grid) {
        int res = 0;
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (!visited[i][j] && grid[i][j] == '1') {
                    dfs(grid, visited, i, j);
                    res++;
                }
            }

        }
        return res;
    }

    private void dfs(char[][] grid, boolean[][] visited, int i, int j) {
        visited[i][j] = true;
        // 右
        if (j + 1 <= grid[0].length - 1 && !visited[i][j + 1] && grid[i][j + 1] == '1') {
            dfs(grid, visited, i, j + 1);
        }
        // 下
        if (i + 1 <= grid.length - 1 && !visited[i + 1][j] && grid[i + 1][j] == '1') {
            dfs(grid, visited, i + 1, j);
        }
        // 左
        if (j - 1 >= 0 && !visited[i][j - 1] && grid[i][j - 1] == '1') {
            dfs(grid, visited, i, j - 1);
        }
        // 上
        if (i - 1 >= 0 && !visited[i - 1][j] && grid[i - 1][j] == '1') {
            dfs(grid, visited, i - 1, j);
        }
    }

    @Test
    public void test() {
        char[][] grid = new char[][]{{'1', '1', '1', '1', '0'}, {'1', '1', '0', '1', '0'}, {'1', '1', '0', '0', '0'},
            {'0', '0', '0', '0', '0'}
        };
        System.out.println(numIslands(grid));
    }

}
    